package ar.edu.itba.bundundu;

import java.io.IOException;
import java.net.URL;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.facebookapi.FacebookParam;
import com.google.gdata.client.calendar.CalendarService;

import com.google.gdata.data.Link;
import com.google.gdata.data.acl.AclEntry;
import com.google.gdata.data.acl.AclFeed;
import com.google.gdata.data.acl.AclNamespace;

import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarFeed;

import ar.edu.itba.bundundu.dao.UserDao;
import ar.edu.itba.bundundu.domain.CalendarItem;
import ar.edu.itba.bundundu.domain.CalendarSharing;
import ar.edu.itba.bundundu.domain.UserIds;



public class ShareCalendarsServlet extends HttpServlet{
  private static final long serialVersionUID = 1L;

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    try{
      RequestDispatcher dispatcher;
      dispatcher = getServletContext().getRequestDispatcher("/sharecalendars.jsp");
      Facebook facebook = new Facebook(req.getParameter(FacebookParam.SESSION_KEY
          .toString()));
      Long uid = facebook.getUserId();
      String uids=facebook.getUidsAppFriends();
      req.setAttribute("uid", uid);
      req.setAttribute("uids", uids);
      UserIds user = UserDao.getUser(uid);
      String sessionToken = user.getToken();
      CalendarService service = new CalendarService("exampleCo-exampleApp-1");
      service.setAuthSubToken(sessionToken, null);
      CalendarFeed calendarFeed =
        service.getFeed(new URL(
            "http://www.google.com/calendar/feeds/default/owncalendars/full"),
            CalendarFeed.class);
      CalendarSharing calendar = new CalendarSharing();
      for (CalendarEntry calEntry : calendarFeed.getEntries()) {
        Link link = calEntry.getLink(AclNamespace.LINK_REL_ACCESS_CONTROL_LIST,
          Link.Type.ATOM); 
        CalendarItem item = new CalendarItem(calEntry.getTitle().getPlainText(),
            calEntry.getId());
      // For each calendar, retrieve its ACL feed.
      AclFeed aclFeed = service.getFeed(new URL(link.getHref()), AclFeed.class);
      for(AclEntry aclEntry : aclFeed.getEntries()) {
        item.addFeed(aclEntry.getScope().getValue(),  
            aclEntry.getTitle().getPlainText(), aclEntry);
        
        }
        calendar.addItem(item);
      }
      req.setAttribute("calendars", calendar);
      dispatcher.forward(req, resp);
     }catch(Exception e){
      //e.printStackTrace();
       //req.setAttribute("err", "");
       //TODO manejar esto bien cuando hay una exception (mandar un error en el req y atraparlo desde el jsp)
     }
  }
  
}
